﻿using System;
using System.Linq;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Runtime.InteropServices;

namespace NewProcessGuarder.toolFunc
{
    /// <summary>
    /// 进程操作辅助类
    /// 功能：根据应用程序路径启动、终止程序（进程），判断进程是否存在（程序是否启动）
    /// </summary>
    public static class ProcessFunc
    {
        #region 根据文件路径查找并终止进程
        /// <summary>
        /// 根据文件路径查找并终止进程
        /// </summary>
        /// <param name="appPath"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static bool KillProcessByPath(string appPath)
        {
            string processName = "";
            string processNameExt = "";
            try
            {

                if (File.Exists(appPath))
                {
                    processName = Path.GetFileNameWithoutExtension(appPath);
                    processNameExt = Path.GetFileName(appPath);
                }
                else throw new FileNotFoundException("给定的文件不存在");

                if (ProcessExists(appPath))
                {
                    var ps = Process.GetProcessesByName(processName);
                    ps.ToList().ForEach((p) => { p.Kill(); });
                    int i = 0;
                    while (i <= 5 && ProcessExists(appPath))
                    {
                        System.Threading.Thread.Sleep(200);
                        i++;
                    }


                    var psExt = Process.GetProcessesByName(processNameExt);
                    psExt.ToList().ForEach((p) => { p.Kill(); });
                    while (i <= 5 && ProcessExists(appPath))
                    {
                        System.Threading.Thread.Sleep(200);
                        i++;
                    }

                }
                bool result = !ProcessExists(appPath);

                return result;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        #endregion

        #region 启动程序
        /// <summary>
        /// 启动程序
        /// </summary>
        /// <param name="appPath"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static bool StartProcessByPath(string appPath)
        {
            try
            {
                if (File.Exists(appPath))
                {
                    //必须有工作路径
                    ProcessStartInfo si = new ProcessStartInfo();
                    si.FileName = appPath;
                    si.WorkingDirectory = Path.GetDirectoryName(appPath);

                    //判断配置文件中取到的延时时间设置是否合法，并根据设置延时启动程序
                    System.Text.RegularExpressions.Regex rex = new System.Text.RegularExpressions.Regex(@"^\d+$");
                    if (!string.IsNullOrEmpty(AppSetting.Get("TimeDelay")) && rex.IsMatch(AppSetting.Get("TimeDelay")))
                    {
                        Thread.Sleep(Int32.Parse(AppSetting.Get("TimeDelay")));
                    }

                    Process.Start(si);
                }
                else
                {
                    if (AutoStart.IsAutoRun(appPath))
                    {
                        AutoStart.EraseAutoRun(appPath);
                    }
                }
                //throw new FileNotFoundException("给定的应用程序不存在");

                //string pname = Path.GetFileNameWithoutExtension(appPath);
                int i = 0;
                while (!ProcessExists(appPath) && i <= 5)
                {
                    System.Threading.Thread.Sleep(200);
                    i++;
                }

                return ProcessExists(appPath);
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        #endregion

        #region 重启进程
        public static void RestartApplication(string appPath)
        {
            if (KillProcessByPath(appPath))
                StartProcessByPath(appPath);
        }
        #endregion

        #region 判断进程是否存在
        /// <summary>
        /// 判断进程是否存在
        /// </summary>
        /// <param name="appPath"></param>
        /// <returns></returns>
        public static bool ProcessExists(string appPath)
        {
            string pname = Path.GetFileNameWithoutExtension(appPath);
            string bname = Path.GetFileName(appPath);
            
            //IntPtr ip1 = FindWindow(null, "MainWindow");
            //IntPtr ip2 = GetForegroundWindow();
            //bool resultCurrent = ( ip1==ip2 );
            //System.Windows.Forms.MessageBox.Show(ip1.ToString() + ";"+ ip2.ToString());
            bool resultb = Process.GetProcessesByName(bname).Count() > 0;
            bool result = Process.GetProcessesByName(pname).Count() > 0;
            return result || resultb;
        }
        #endregion

        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    }
}
